﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Argotic.Syndication;
using Argotic.Data.Adapters;
using Argotic.Common;
using System.Xml.XPath;

namespace MyPublish.Connection.Syndication.LiveSpace
{
    [DataConnectionProvider(Name = "LiveSpace", Type = typeof(SpaceConnectionProvider))]
    public class SpaceConnectionProvider : DataConnectionProvider
    {
        //{0}:<alias> {categoryID} {blogentryid}
        public const string ALL_FEEDS_URI_FORMAT = "http://{0}.spaces.live.com/blog/feed.rss";
        public const string CATEGORY_FEED_URI_FORMAT = "http://{0}.spaces.live.com/category/{1}/feed.rss";
        public const string COMMENTS_FEED_URI_FORMAT = "http://{0}.spaces.live.com/blog/{1}/feed.rss";

        private LiveSpacesMetaWeblog _webBlog;
        private LiveSpacesMetaWeblog WebBlog
        {
            get
            {
                if (_webBlog == null)
                {
                    _webBlog = new LiveSpacesMetaWeblog();
                    if (Proxy != null)
                    {
                        _webBlog.Credentials = Proxy.Credentials;
                    }
                }
                return _webBlog;
            }
        }

        public override IEnumerable<object> ExecuteQuery()
        {
            List<object> items = new List<object>();

            UserBlog[] blogs = WebBlog.getUsersBlogs(string.Empty, ConnectionString.UserName, ConnectionString.Password);
            foreach (UserBlog blog in blogs)
            {
                items.Add(new BlogData()
                {
                    ID = blog.blogid,
                    BlogURL = blog.url,
                    Title = blog.blogName,
                    UserName = ConnectionString.UserName,
                    FeedURL = string.Format(ALL_FEEDS_URI_FORMAT, ConnectionString.UserName),
                    PostURL = string.Empty,
                    SelfFeedURL = string.Format(ALL_FEEDS_URI_FORMAT, ConnectionString.UserName)
                });
            }

            return items;
        }

        public override IEnumerable<object> ExecuteQuery(object data)
        {
            BlogData blogdata = data as BlogData;
            RssFeedContext context = RssFeedContext.Create(blogdata.Url, blogdata.Title);
            foreach (PostData post in context.Posts)
            {
                yield return post;
            }
        }
    }
}
